﻿using Dyao.Book.Contract;

namespace Dyao.Book.Application.Abstractions
{
    public static class TaskCenterRequestParamsSerializerExtensions
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serializer"></param>
        /// <param name="model"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static Task<T> DeserializeAsync<T>(this ITaskCenterRequestParamsSerializer serializer, TaskCenterDto model, CancellationToken cancellationToken = default)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            return serializer.DeserializeAsync<T>(model.TaskCenterRecordId, model.TaskCode, ParseCategory(model.Category), cancellationToken);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="serializer"></param>
        /// <param name="model"></param>
        /// <param name="requestParams"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static Task<string> SerializeAsync(this ITaskCenterRequestParamsSerializer serializer, TaskCenterDto model, object requestParams, CancellationToken cancellationToken = default)
        {
            return serializer.SerializeAsync(model?.TaskCode, ParseCategory(model?.Category), requestParams, cancellationToken);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="serializer"></param>
        /// <param name="actionKey"></param>
        /// <param name="catetory"></param>
        /// <param name="requestParams"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static Task<string> SerializeAsync(this ITaskCenterRequestParamsSerializer serializer, string actionKey, string catetory, object requestParams, CancellationToken cancellationToken = default)
        {
            return serializer.SerializeAsync(actionKey, ParseCategory(catetory), requestParams, cancellationToken);
        }

        private static TaskCenterCategoryEnum ParseCategory(string categoryStr)
        {
            TaskCenterCategoryEnum category = default;
            if (!string.IsNullOrWhiteSpace(categoryStr))
            {
                Enum.TryParse(categoryStr, out category);
            }

            return category;
        }
    }
}
